package com.fenfen.novel;

import android.app.Dialog;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.fenfen.novel.adapter.ChapterAdapter;
import com.fenfen.novel.db.NovelReadRecord;
import com.fenfen.novel.fragment.ChapterFragment;
import com.fenfen.novel.model.Chapter;
import com.fenfen.novel.utils.ChapterListUtil;
import com.fenfen.novel.utils.CommonUtil;
import com.fenfen.novel.utils.NovelFileCallbackListener;
import com.fenfen.novel.utils.NovelFileUtils;
import com.fenfen.novel.utils.NovelRecordHandlerThread;
import com.fenfen.novel.utils.NovelRecordUtil;
import com.fenfen.novel.utils.SharedPrefsUtils;
import com.fenfen.novel.utils.SystemUiHelper;

import org.parceler.Parcels;

import java.util.ArrayList;

public class ChapterActivity extends BaseActivity implements ChapterAdapter.ChapterClickListener {
  private static String Tag = ChapterActivity.class.getSimpleName();

  public static final String EXTRA_CHAPTER = "chapter";

  public static final String EXTRA_CHAPTER_COUNT = "chapter_count";

  private Chapter chapter;
  private int chapterCount;

  private ViewPager mViewPager;
  private ViewPagerAdapter mViewPagerAdapter;
  private View bottomControlView;
  private Toolbar toolbar;

  private DrawerLayout drawerLayout;
  private RecyclerView recyclerChapterList;
  private ChapterListUtil chapterListUtil;
  private ChapterAdapter chapterAdapter;

  private SystemUiHelper uiHelper;
  private boolean mSystemUiVisible;

  private ProgressBar loadingProgress;
  private MyCallbackListener mCallbackListener;

  private SeekBar chapterSeekBar;
  private TextView popupChapterTitleTv;
  private TextView popupChapterProgressTv;

  private FloatingActionButton fabNightMode;

  private EditText jumpOrder;

  private boolean isChangeThemeBtnClick = false; //是否点击切换夜间模式按钮

  private NovelRecordHandlerThread dbThread; //更新阅读记录线程
  private boolean isDownload; //是否下载

  private boolean isSeekBarEnd; //是否章节SeekBar结束滑动

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     /*set it to be no title*/
//    requestWindowFeature(Window.FEATURE_NO_TITLE);
       /*set it to be full screen*/
//    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//        WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.activity_chapter);

    chapterListUtil = new ChapterListUtil(this);
    int level = SystemUiHelper.LEVEL_IMMERSIVE;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
      level = SystemUiHelper.LEVEL_HIDE_STATUS_BAR;
    }
    uiHelper = new SystemUiHelper(this, level, SystemUiHelper.FLAG_IMMERSIVE_STICKY, new SystemUiHelper.OnVisibilityChangeListener() {
      @Override
      public void onVisibilityChange(boolean visible) {
        mSystemUiVisible = visible;
      }
    });

    initIntentData();

    initToolbar();
    initView();

    dbThread = new NovelRecordHandlerThread(this, new Handler());
    dbThread.start();
    dbThread.getLooper();
    dbThread.setHandlerListener(new MyDbListener());

    initDownloadStatus();

    initScreenLight();
  }

  private void initDownloadStatus() {
    dbThread.queryDownInfoByNovelId(chapter.getNovelId());
  }

  private void updateDrawerLayoutListPos() {
    int pos = mViewPager.getCurrentItem();
//    recyclerChapterList.scrollToPosition(pos);
    int recyclerHeight = recyclerChapterList.getMeasuredHeight();
    ((LinearLayoutManager) recyclerChapterList.getLayoutManager()).scrollToPositionWithOffset(pos, recyclerHeight / 2);
    chapterAdapter.setCurrentChapter(pos);
  }

  @Override
  protected void onResume() {
    super.onResume();
    isChangeThemeBtnClick = false; //reset
    setNightMask();
  }

  @Override
  protected void onPause() {
    super.onPause();
    if (!isChangeThemeBtnClick) {
      CommonUtil.removeNightMask(this);
    }
  }

  private void setNightMask() {
    boolean isNight = SharedPrefsUtils.getInstance(this).getChapterNightMode();
    if (isNight) {
      CommonUtil.addNightMask(this);
    } else {
      CommonUtil.removeNightMask(this);
    }
  }

  private void initScreenLight() {
    boolean isNight = SharedPrefsUtils.getInstance(this).getChapterNightMode();
    changeBrightness(isNight, this);
  }

  private void initIntentData() {
    chapterCount = getIntent().getIntExtra(EXTRA_CHAPTER_COUNT, CommonUtil.ZERO_INT_DATA);
    chapter = Parcels.unwrap(getIntent().getParcelableExtra(EXTRA_CHAPTER));
  }

  private void initView() {

    recyclerChapterList = (RecyclerView) findViewById(R.id.chapters_list);
    chapterAdapter = new ChapterAdapter(ChapterActivity.this);
    chapterListUtil.initChaptersRecyclerView(recyclerChapterList, false, chapterAdapter);

    loadingProgress = (ProgressBar) findViewById(R.id.loading);
    CommonUtil.filterProgressColor(this, loadingProgress);
    mCallbackListener = new MyCallbackListener();

//    mViewPager.setPageTransformer(true, new PageSlideTransformer());

    bottomControlView = findViewById(R.id.chapter_control_bottom);

    chapterSeekBar = (SeekBar) findViewById(R.id.chapter_seek);
    chapterSeekBar.setMax(chapterCount - 1);
    chapterSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
      @Override
      public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        isSeekBarEnd = false;
        if (checkChapterListData() && fromUser) {
          updateProgressPopupWindow(seekBar);
        }
      }

      @Override
      public void onStartTrackingTouch(SeekBar seekBar) {
        isSeekBarEnd = false;
        if (checkChapterListData()) {
          showProgressPopupWindow(seekBar);
        }
      }

      @Override
      public void onStopTrackingTouch(SeekBar seekBar) {
        isSeekBarEnd = true;
        if (checkChapterListData()) {
          Log.d(Tag, "onStopTrackingTouch: progress=" + seekBar.getProgress());
          int progress = seekBar.getProgress();
          int currentPos = mViewPager.getCurrentItem();
          dismissPopUpWindow();
          if (progress == currentPos) {
            return;
          }
          showProgress();
          getSupportActionBar().setTitle(chapterAdapter.getData().get(progress).getChapterTitle());
          mViewPager.setCurrentItem(progress);
        }
      }
    });

    mViewPager = (ViewPager) findViewById(R.id.chapter_view_pager);

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
      @Override
      public void onDrawerSlide(View drawerView, float slideOffset) {

      }

      @Override
      public void onDrawerOpened(View drawerView) {
        Log.d(Tag, "drawerView open");
        toggleFullScreenUI(false);
//        TODO:init  and set current chapter item textcolor to red
      }

      @Override
      public void onDrawerClosed(View drawerView) {
        Log.d(Tag, "drawerView closed");
        if (jumpOrder != null) {
          CommonUtil.hideSoftInputMethod(ChapterActivity.this, jumpOrder);
        }
      }

      @Override
      public void onDrawerStateChanged(int newState) {
        Log.d(Tag, "drawerView state changed-->" + newState);
      }
    });

    TextView novelChapterCount = (TextView) findViewById(R.id.novel_chapter_count);
    novelChapterCount.setText(String.format(getString(R.string.novel_chapter_count_pre), chapterCount));
    jumpOrder = (EditText) findViewById(R.id.jump_chapter_order);
    jumpOrder.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
          //hide keyboard
          CommonUtil.hideSoftInputMethod(ChapterActivity.this, jumpOrder);
          toggleFullScreenUI(hasFocus);
        }
      }
    });

    jumpOrder.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (TextUtils.isEmpty(s)) {
          return;
        }
        if (!TextUtils.isDigitsOnly(s)) {
          //remove it from edittext
          jumpOrder.getEditableText().delete(start, start + count);
          Snackbar.make(drawerLayout, getString(R.string.chpater_order_only_number), Snackbar.LENGTH_SHORT).show();
        }
      }

      @Override
      public void afterTextChanged(Editable s) {
        if (!TextUtils.isEmpty(s) && TextUtils.isDigitsOnly(s.toString())) {
          int chapterOrder = Integer.parseInt(s.toString());
          if (chapterOrder <= 0 || chapterOrder > chapterCount) {
            Snackbar.make(drawerLayout, getString(R.string.chapter_order_large_than_count), Snackbar.LENGTH_SHORT).show();
            return;
          }
          if (recyclerChapterList != null) {
            int pos = chapterOrder - 1;
//            recyclerChapterList.scrollToPosition(pos);
            int recyclerHeight = recyclerChapterList.getMeasuredHeight();
            ((LinearLayoutManager) recyclerChapterList.getLayoutManager()).scrollToPositionWithOffset(pos, recyclerHeight / 2);
//            recyclerChapterList.findViewHolderForAdapterPosition(chapterOrder - 1).itemView.performClick();
          }
        }
      }
    });

    fabNightMode = (FloatingActionButton) findViewById(R.id.fab_night_mode);
    boolean isNight = SharedPrefsUtils.getInstance(this).getChapterNightMode();
    if (isNight) {
      fabNightMode.setImageResource(R.drawable.ic_day);
    } else {
      fabNightMode.setImageResource(R.drawable.ic_night);
    }
    fabNightMode.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        isChangeThemeBtnClick = true;
        chapter.setChapterOrder(mViewPager.getCurrentItem() + 1);
        notifyAllChangeTheme();
        //update1,screenshot first and after recreate(),alpha the pic
        //update2,no recreate(),update the view by manual
      }
    });
  }

  private void updateProgressPopupWindow(SeekBar seekBar) {
    if (progressPopup == null || !progressPopup.isShowing()) {
      showProgressPopupWindow(seekBar);
    }
    int progress = seekBar.getProgress();
    popupChapterProgressTv.setText(String.format(getString(R.string.chapter_progress), progress + 1, chapterCount));
    if (chapterAdapter.getItemCount() > progress) {
      popupChapterTitleTv.setText(chapterAdapter.getData().get(progress).getChapterTitle());
    }
  }

  private PopupWindow progressPopup;

  private void dismissProgressPopUpWindow() {
    if (progressPopup != null && progressPopup.isShowing()) {
      progressPopup.dismiss();
    }
  }

  private boolean checkChapterListData() {
    if (chapterAdapter.getData() != null && chapterAdapter.getData().size() > 0) {
      return true;
    }
    return false;
  }

  private void showProgressPopupWindow(SeekBar seekBar) {
    int navigationBarHeight = CommonUtil.getNavigationBarHeight(this);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT ||
        this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
      navigationBarHeight = 0;
    }
    int y = bottomControlView.getMeasuredHeight() + navigationBarHeight + 20;
    if (progressPopup != null) {
      if (!progressPopup.isShowing()) {
        progressPopup.showAtLocation(seekBar, Gravity.BOTTOM, 0, y);
      }
      return;
    }

    View popupView = getLayoutInflater().inflate(R.layout.popup_chapter_progress, null);

    LinearLayout rootLayout = (LinearLayout) popupView.findViewById(R.id.pop_root_view);
    CommonUtil.filterDrawableColor(this, rootLayout.getBackground(), R.attr.colorPrimary);

    popupChapterTitleTv = (TextView) popupView.findViewById(R.id.popup_chapter_title);
    popupChapterProgressTv = (TextView) popupView.findViewById(R.id.popup_chapter_progress);

    popupChapterTitleTv.setText(chapter.getChapterTitle());
    popupChapterProgressTv.setText(String.format(getString(R.string.chapter_progress), seekBar.getProgress() + 1, chapterCount));

    progressPopup = new PopupWindow(popupView,
        CommonUtil.getDevicePxWidth() * 3 / 4, LinearLayout.LayoutParams.WRAP_CONTENT, true);

    progressPopup.setTouchable(true);
    progressPopup.setOutsideTouchable(true);

    // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
    // 我觉得这里是API的一个bug
    progressPopup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    // 设置好参数之后再show
    progressPopup.showAtLocation(seekBar, Gravity.BOTTOM, 0, y);
  }

  private void initToolbar() {
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(chapter.getChapterTitle());
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        super.onBackPressed();
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override
  public void onBackPressed() {
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
      drawerLayout.closeDrawer(GravityCompat.START);
      return;
    }
    super.onBackPressed();
  }

  private void toggleSystemUI(boolean isShow) {
    if (isShow) {
      uiHelper.show();
    } else {
      uiHelper.delayHide(300);
//      uiHelper.hide();
    }
  }

  public boolean getFullScreenIsShowing() {
    return mSystemUiVisible;
  }

  @Override
  public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
//      showSystemUI();
//      hideViewUI();
//      showViewUI();
    if (hasFocus) {
      toggleFullScreenUI(!hasFocus);
    }
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
  }

  public void toggleFullScreenUI(boolean isShow) {
    toggleViewUI(isShow);
    toggleSystemUI(isShow);
  }

  private void toggleViewUI(boolean isShow) {
    int statusBarHeight = CommonUtil.getStatusBarHeight(this);
    int navigationBarHeight = CommonUtil.getNavigationBarHeight(this);

    int topY = toolbar.getMeasuredHeight();

    topY = isShow ? statusBarHeight : -topY;
    translationYAnimate(toolbar, topY, isShow);

    int bottomY = bottomControlView.getMeasuredHeight();
    if (isShow) {
      bottomY = -navigationBarHeight;
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT || this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        bottomY = 0;
      }
    }
    translationYAnimate(bottomControlView, bottomY, isShow);
    Log.d(Tag, "isShow=" + isShow + ",toolbar.getMeasuredHeight()="
        + toolbar.getMeasuredHeight() + ",statusBarHeight=" + statusBarHeight + ",topY=" + topY);
    Log.d(Tag, "isShow=" + isShow + ",bottomControlView.getMeasuredHeight()="
        + bottomControlView.getMeasuredHeight() + ",navigationBarHeight=" + navigationBarHeight + ",bottomY=" + bottomY);
    if (isShow) {
      fabNightMode.show(new FloatingActionButton.OnVisibilityChangedListener() {
        @Override
        public void onShown(FloatingActionButton fab) {
          super.onShown(fab);
        }
      });
    } else {
      fabNightMode.hide(new FloatingActionButton.OnVisibilityChangedListener() {
        @Override
        public void onHidden(FloatingActionButton fab) {
          super.onHidden(fab);
        }
      });
    }
  }

  private void translationYAnimate(View v, int y, boolean isShow) {
    v.animate().translationY(y).setInterpolator(new AccelerateInterpolator()).setStartDelay(isShow ? 0 : 100);
  }

  @Override
  public void onItemClick(View v, Chapter chapter) {
    //show chapter that was clicked,except it's already current chapter
    //and close the drawerlayout
//    showChapterInfo(chapter);
    int chapterOrder = chapter.getChapterOrder();
    int currentItem = mViewPager.getCurrentItem();
    if (chapterOrder == currentItem + 1) {
      return;
    }
    toggleFullScreenUI(false);
    drawerLayout.closeDrawer(GravityCompat.START);
    showProgress();
    getSupportActionBar().setTitle(chapter.getChapterTitle());
    mViewPager.setCurrentItem(chapterOrder > 0 ? chapterOrder - 1 : chapterOrder);
  }

  public void onBottomClick(View v) {
    switch (v.getId()) {
      case R.id.btn_chapter_list:
        if (!drawerLayout.isDrawerOpen(GravityCompat.START)) {
          drawerLayout.openDrawer(GravityCompat.START);
        }
        break;
      case R.id.btn_pre_chapter:
        int pos = mViewPager.getCurrentItem();
        if (pos <= 0) {
          Snackbar.make(v, getString(R.string.already_first_chapter), Snackbar.LENGTH_SHORT).show();
          return;
        }
        drawerLayout.closeDrawer(GravityCompat.START);
        mViewPager.setCurrentItem(pos - 1);
        break;
      case R.id.btn_next_chapter:
        int currentItem = mViewPager.getCurrentItem();
        if (currentItem + 1 >= chapterCount) {
          Snackbar.make(v, getString(R.string.already_last_chapter), Snackbar.LENGTH_SHORT).show();
          return;
        }
        drawerLayout.closeDrawer(GravityCompat.START);
        mViewPager.setCurrentItem(currentItem + 1);
        break;
      case R.id.btn_chapter_text_size:
        toggleViewUI(false);
        showPopUpWindow(v);
        break;
      case R.id.btn_chapter_light:
        toggleViewUI(false);
        v.postDelayed(new Runnable() {
          @Override
          public void run() {
            showBottomDialog();
          }
        }, 300);
        break;
      case R.id.btn_chapter_setting:
        break;
      default:
        break;
    }
  }

  private Dialog mBottomSheetDialog;

  private void showBottomDialog() {
    if (mBottomSheetDialog != null) {
      if (!mBottomSheetDialog.isShowing()) {
        mBottomSheetDialog.show();
      }
      return;
    }
    mBottomSheetDialog = new Dialog(this, R.style.MaterialDialogSheet);
    View view = getLayoutInflater().inflate(R.layout.dialog_bottom_light, null);
    bindLightBottomClick(view);
    mBottomSheetDialog.setContentView(view);
    mBottomSheetDialog.setCancelable(true);
    mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.WRAP_CONTENT);
    mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
    mBottomSheetDialog.show();
  }

  private void bindLightBottomClick(View v) {
    final SeekBar lightSeekBar = (SeekBar) v.findViewById(R.id.seekbar_light);
    try {
      int brightness = CommonUtil.getCurrentLight(ChapterActivity.this);
      if (brightness == CommonUtil.NONE_INT_DATA) {
        brightness = CommonUtil.CHAPTER_BRIGHTNESS_SHOW_DEFAULT;
      }
      lightSeekBar.setProgress(brightness);
    } catch (Settings.SettingNotFoundException e) {
      e.printStackTrace();
    }

    final CheckBox lightSystemCb = (CheckBox) v.findViewById(R.id.checkbox_light_system);
    if (SharedPrefsUtils.getInstance(ChapterActivity.this).getChapterBrightnessMode() == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
      lightSystemCb.setChecked(true);
    }
    lightSystemCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
//          lightSeekBar.setProgress();
          CommonUtil.changeAppBrightness(ChapterActivity.this, -1);
          //TODO change seekbar background
        } else {
          CommonUtil.changeAppBrightness(ChapterActivity.this, lightSeekBar.getProgress());
          SharedPrefsUtils.getInstance(ChapterActivity.this).setChapterBrightness(lightSeekBar.getProgress());
        }
        SharedPrefsUtils.getInstance(ChapterActivity.this).setChapterBrightnessMode(isChecked ? Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC : Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
      }
    });

    lightSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
      @Override
      public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (lightSystemCb.isChecked()) {
          lightSystemCb.setChecked(false);
        }
        SharedPrefsUtils.getInstance(ChapterActivity.this).setChapterBrightness(progress);
        CommonUtil.changeAppBrightness(ChapterActivity.this, progress);
      }

      @Override
      public void onStartTrackingTouch(SeekBar seekBar) {

      }

      @Override
      public void onStopTrackingTouch(SeekBar seekBar) {

      }
    });
  }

  private PopupWindow popupWindow;

  Runnable r = new Runnable() {
    @Override
    public void run() {
      Log.d(Tag,"runnable:isSeekbarEnd=" + isSeekBarEnd);
      if(isSeekBarEnd) {
        popupWindow.dismiss();
      }
    }
  };

  private void dismissPopUpWindow() {
    if (popupWindow != null && popupWindow.isShowing()) {
      chapterSeekBar.removeCallbacks(r);
      chapterSeekBar.postDelayed(r, 1000);
//      popupWindow.dismiss();
    }
  }

  private void showPopUpWindow(View view) {
    if (popupWindow != null) {
      if (!popupWindow.isShowing()) {
        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, bottomControlView.getMeasuredHeight());
      }
      return;
    }

    final View popupView = getLayoutInflater().inflate(R.layout.popup_change_text_size, null);
    LinearLayout root = (LinearLayout) popupView.findViewById(R.id.pop_root_view);
    CommonUtil.filterDrawableColor(this, root.getBackground(), R.attr.colorPrimary);

    ImageButton btnRaise = (ImageButton) popupView.findViewById(R.id.btn_text_size_raise);
    ImageButton btnReduce = (ImageButton) popupView.findViewById(R.id.btn_text_size_reduce);
    final TextView textSizeTv = (TextView) popupView.findViewById(R.id.chapter_text_size);
    int textSize = SharedPrefsUtils.getInstance(this).getChapterTextSize();
    textSizeTv.setText(String.valueOf(textSize));

    popupWindow = new PopupWindow(popupView,
        LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);

    popupWindow.setTouchable(true);
    popupWindow.setOutsideTouchable(true);

    // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
    // 我觉得这里是API的一个bug
    popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    // 设置好参数之后再show
    popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, bottomControlView.getMeasuredHeight());

    btnRaise.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        ChapterFragment fragment = (ChapterFragment) mViewPagerAdapter.currentFragment;
        int currTextSize = fragment.getChapterTextSize();
        currTextSize++;
        if (currTextSize > CommonUtil.TEXT_SIZE_MAX) {
          currTextSize = CommonUtil.TEXT_SIZE_MAX;
        }
        textSizeTv.setText(String.valueOf(currTextSize));
        SharedPrefsUtils.getInstance(ChapterActivity.this).setChapterTextSize(currTextSize);
        fragment.setChapterTextSize(currTextSize);
        mViewPagerAdapter.notifyDataSetChanged();
      }
    });

    btnReduce.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        ChapterFragment fragment = (ChapterFragment) mViewPagerAdapter.currentFragment;
        int currTextSize = fragment.getChapterTextSize();
        currTextSize--;
        if (currTextSize < CommonUtil.TEXT_SIZE_MIN) {
          currTextSize = CommonUtil.TEXT_SIZE_MIN;
        }
        textSizeTv.setText(String.valueOf(currTextSize));
        SharedPrefsUtils.getInstance(ChapterActivity.this).setChapterTextSize(currTextSize);
        fragment.setChapterTextSize(currTextSize);
        mViewPagerAdapter.notifyDataSetChanged();
      }
    });
  }

  @Override
  public void onLoadAllItemClick(View v) {
    return;
  }

  public void hideProgress() {
    loadingProgress.setVisibility(View.GONE);
  }

  public void showProgress() {
    loadingProgress.setVisibility(View.VISIBLE);
  }

  public MyCallbackListener getCallbackListener() {
    return mCallbackListener;
  }

  private class ViewPagerAdapter extends FragmentStatePagerAdapter {
    Fragment currentFragment;

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
      super.setPrimaryItem(container, position, object);
      if (currentFragment == object) {
        return;
      }
      currentFragment = (Fragment) object;
      //after viewpager scroll then set primary item,now update toolbar title and other
      ChapterFragment fragment = (ChapterFragment) currentFragment;
      fragment.setCurrentPos(position);
      byte dataLoadStatus = fragment.getDataLoadStatus();
      switch (dataLoadStatus) {
        case CommonUtil.DATA_STATUS.NOT_START:
          break;
        case CommonUtil.DATA_STATUS.REQUEST:
          showProgress();
          break;
        case CommonUtil.DATA_STATUS.NO_DATA:
          mCallbackListener.onFailure();
          break;
        case CommonUtil.DATA_STATUS.SUCCESS:
          mCallbackListener.onResponse();
          break;
        case CommonUtil.DATA_STATUS.FAIL:
          mCallbackListener.onFailure();
          break;
        default:
          break;
      }
    }

    public ViewPagerAdapter(FragmentManager fm) {
      super(fm);
    }

    @Override
    public Fragment getItem(int position) {
      Bundle bundle = new Bundle();
//      bundle.putInt(EXTRA_CHAPTER_ID, chapterId);
//      bundle.putInt(EXTRA_NOVEL_ID, novelId);
      bundle.putInt(ChapterFragment.BUNDLE_POS, position);
      return ChapterFragment.newInstance(bundle);
    }

    @Override
    public int getItemPosition(Object object) {
      //update textSize when notifyDataSetChanged called
      int textSize = SharedPrefsUtils.getInstance(ChapterActivity.this).getChapterTextSize();
      ChapterFragment fragment = (ChapterFragment) object;
      if (fragment != null) {
        fragment.setChapterTextSize(textSize);
      }
      return super.getItemPosition(object);
    }

    @Override
    public int getCount() {
      return chapterCount;
    }
  }

  private void setToolbarTitle() {
    ChapterFragment fragment = (ChapterFragment) mViewPagerAdapter.currentFragment;
    if (fragment != null) {
      String chapterTitle = fragment.getChapterTitle();
      if (!TextUtils.isEmpty(chapterTitle)) {
        getSupportActionBar().setTitle(chapterTitle);
      }
    }
  }

  private class ChapterViewPagerChangeListener implements ViewPager.OnPageChangeListener {

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
      Log.d(Tag, "onPageSelected: position=" + position);
      //update drawer layout scroll
      updateDrawerLayoutListPos();
      //update seekbar progress
      chapterSeekBar.setProgress(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
  }

  private class MyCallbackListener implements CommonUtil.CallbackListener {

    @Override
    public void onResponse() {
      hideProgress();
      setToolbarTitle();
      ChapterFragment fragment = (ChapterFragment) mViewPagerAdapter.currentFragment;
      if (fragment != null) {
        fragment.chapterScrollToPos();
        //update read record
        if (chapter == null) {
          return;
        }
        Chapter updateChapter = fragment.getChapter();
        if (updateChapter != null) {
          NovelReadRecord record = NovelRecordUtil.convertToRecordWithChapter(chapter.getNovelId(), updateChapter);
          dbThread.updateRecordWithChapter(record);
        }
      }
    }

    @Override
    public void onFailure() {
      hideProgress();
      CommonUtil.showSnackRetry(loadingProgress, R.string.get_chapter_content_error, new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          showProgress();
//            loadChapter();
          ChapterFragment fragment = (ChapterFragment) mViewPagerAdapter.currentFragment;
          if (isDownload) {
            fragment.loadChapterFromLocal();
          } else {
            fragment.loadChapter();
          }
        }
      });
    }
  }

  private class MyDbListener extends NovelRecordHandlerThread.HandlerListener {
    @Override
    public void onQueryDownStatus(String status) {
      Log.d(Tag, "isDownload=" + status);
      if (status.equals(CommonUtil.DOWN_STATUS.SUCCESS) && CommonUtil.isNovelFileExist(ChapterActivity.this, chapter.getNovelId())) {
        isDownload = true;
        NovelFileUtils.getInstance().getFileChapterList(CommonUtil.getNovelFilePath(ChapterActivity.this, chapter.getNovelId()), new NovelFileCallbackListener() {
          @Override
          public void onChapterListFinish(final ArrayList<String> chapterTitleList) {
            super.onChapterListFinish(chapterTitleList);
            final String costTime = getCost();
            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                if (!TextUtils.isEmpty(costTime)) {
                  CommonUtil.showSnack(loadingProgress, String.format(getString(R.string.cost_time), costTime));
                }
                if (chapterTitleList == null || chapterTitleList.size() == 0) {
                  return;
                }
                ArrayList<Chapter> chapterList = NovelFileUtils.getInstance().convertChapterTitleList(chapterTitleList, chapter.getNovelId());
                chapterAdapter.setData(chapterList);
                if (checkChapterListData()) {
                  //update the current pos
                  //scroll to the right pos
                  updateDrawerLayoutListPos();
                }
              }
            });
          }
        });
      } else {
        isDownload = false;
        chapterListUtil.loadNovelChaptersAll(chapter.getNovelId(), chapterAdapter, new CommonUtil.CallbackListener() {
          @Override
          public void onResponse() {
            if (checkChapterListData()) {
              //update the current pos
              //scroll to the right pos
              updateDrawerLayoutListPos();
            }
          }

          @Override
          public void onFailure() {
            //do nothing or retry?
//        chapterListUtil.loadNovelChaptersAll(chapter.getNovelId(), chapterAdapter, this);
          }
        });
      }
      initViewPager();
    }
  }

  private void initViewPager() {
    int chapterOrder = chapter.getChapterOrder();

    mViewPager.setOffscreenPageLimit(5);
    mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
    mViewPager.setAdapter(mViewPagerAdapter);
    mViewPager.addOnPageChangeListener(new ChapterViewPagerChangeListener());

    mViewPager.setCurrentItem(chapterOrder > 0 ? chapterOrder - 1 : chapterOrder);
    Log.d(Tag, "chapterOrder=" + chapterOrder + ",current item=" + mViewPager.getCurrentItem());
  }

  public boolean getDownloadStatus() {
    return isDownload;
  }
}
